var formidable = require("formidable");
var db = require("../models/db.js");
var md5 = require("../models/md5.js");
var path = require("path");
var fs = require("fs");
var gm = require("gm");

exports.showIndex = function(req,res,next){
    if(req.session.login =="1"){        // 登录的话，就检索数据库，查头像
        var username = req.session.username 
        var login = true;
    }else{
        var username = "";
        var login = false;
    }
    db.find("users",{username:req.session.username},function(err,result){
        if(result.length == 0){
            var avatar = "default.jpg";
        }else{
            var avatar = result[0].avatar;
        }
        res.render("index",{
            "login" : login,
            "username" : username,
            "active" : "Index",
            "avatar" : avatar,          // 登录人的头像
        });
    });
}

exports.showRegist = function(req,res,next){                // 注册页面
    res.render("regist",{
        "login" : req.session.login == "1" ? true : false,
        "username" : req.session.login == "1" ? req.session.username : "",
        "active" : "Regist"
    });    
}

exports.doregist = function(req,res,next){              // 注册业务
    var form = new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        var username = fields.username;
        var password = fields.password;
        db.find("users",{"username":username},function(err,result){
            if(err){
                res.send("-3");         // 服务器错误
                return;
            }
            if(result.length != 0){
                res.send("-1");
                return;         
            }
            password = md5(password) + "william";           // 自定义给密码加密
            db.insertOne("users",{      // 用户名没有被占用
                "username" : username,
                "password" : password,
                "avatar" : "default.jpg"
            },function(err,result){
                if(err){
                    res.send("-3");
                    return;
                }
                req.session.login = "1";
                req.session.username = username;
                res.send("1");      // 注册成功，写入Session
            });
        });
    });
}

exports.showLogin = function(req,res,next){
    res.render("login",{
        "login" : req.session.login == "1" ? true : false,
        "username" : req.session.login == "1" ? req.session.username : "",
        "active" : "Login"
    });
}

exports.doLogin = function(req,res,next){       // 登录业务
    var form = new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        var username = fields.username;
        var password = fields.password;
        db.find("users",{"username":username},function(err,result){     // 查询数据库
            password = md5(password) + "william";           // 自定义给密码加密                  
            if(err){
                res.send(err);
                return;
            }
            if(result == 0){            // 没有此用户
                res.send("-1");
                return;
            }
            if(password == result[0].password){
                req.session.login = "1";
                req.session.username = username;
                res.send("1");
                return;
            }else{
                res.send("-2");
                return;
            }
        })
    })
}

exports.showSetavatar = function(req,res,next){         // 设置头像
    if(req.session.login != "1"){
        res.send("请登录之后才可以执行");
        return;
    }
    res.render("Setavatar",{
        "login" : true,
        "username" : req.session.username || "周柏豪",
        "active" : "修改头像"
    });
}

exports.doSetavatar = function(req,res,next){
    if(req.session.login != "1"){
        res.send("请登录之后才可以执行");
        return;
    }
    var form = new formidable.IncomingForm();
    form.uploadDir = path.normalize(__dirname + "/../avatar");
    form.parse(req,function(err,fields,files){
        var oldpath = files.headPortrait.path;
        var newpath = path.normalize(__dirname + "/../avatar") + "/" + req.session.username +".jpg";
        fs.rename(oldpath,newpath,function(err){            // 更换头像的文件名
            if(err){
                res.send("上传失败");
                return;
            }
            req.session.avatar = req.session.username + ".jpg";
            res.redirect("/cut");               // 跳转到裁剪图片的页面
        });
    });
}

exports.showCut = function(req,res){
    res.render("cut",{
        avatar : req.session.avatar
    });
}

exports.docut = function(req,res,next){             // 裁剪头像
    if(req.session.login != "1"){
        res.send("请登录之后才可以执行");
        return;
    }
    var filename = req.session.avatar;
    var w = req.query.w;
    var h = req.query.h;
    var x = req.query.x;
    var y = req.query.y;
    gm("./avatar/" + filename)
        .crop(w,h,x,y)
        .resize(100,100,"!")        // 强行转换为100*100
        .write("./avatar/" + filename,function(err){
        if(err){
            res.send("-1");
            return;
        }
        db.updateMany("users",{"username":req.session.username},{       // 更新数据库的头像图片
            $set : {"avatar" : req.session.avatar}},function(err,results){
                res.send("1");        
        })
    });
}

exports.dopost = function(req,res,next){            // 发表说说
    if(req.session.login != "1"){
        res.end("请登录之后再进行操作");
        return;
    }
    var form = new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        var username = req.session.username;                
        var content = fields.content;
            db.insertOne("content",{      
                "username" : username,
                "datetime" : new Date(),
                "content" : content
            },function(err,result){
                if(err){
                    res.send("-3");
                    return;
                }
                req.session.login = "1";
                res.send("1");      
        });
    })
}

exports.getAllshuoshuo = function(req,res,next){            // 所有说说，有分页
    var page = req.query.page;
    db.find("content",{},{"pageamount":5,"page":page,"sort":{"datetime":-1}},function(err,result){
        res.json(result);
    });
}

exports.getUserinfo = function(req,res,next){               // 列出某个用户的信息
    var username = req.query.username;
    db.find("users",{"username" : username},function(err,result){
        var obj = {
            "username" : result[0].username,
            "avatar" : result[0].avatar,
            "_id" : result[0]._id
        }
        res.json(obj);
    });
}

exports.getAllamount = function(req,res,next){              // 说说总数
    db.getAllCount("content",function(count){
        res.send(count.toString());
    })
}

exports.showUser = function(req,res,next){                  // 用户个人主页
    var user = req.params["user"];
    db.find("content",{"username":user},function(err,result){
        db.find("users",{"username":user},function(err,result2){
            res.render("user",{
                "login" : req.session.login == "1" ? true : false,
                "username" : req.session.login == "1" ? req.session.username : "",
                "user" : user,          // 要查看的用户
                "active" : '我的说说',
                "Thisshuo" : result,
                "Thishead" : result2[0].avatar,
            });
        });
    }); 
}

exports.showUserlist = function(req,res,next){              // 显示用户列表
    db.find("users",{},function(err,result){
        res.render("userlist",{
            "login" : req.session.login == "1" ? true : false,
            "username" : req.session.login == "1" ? req.session.username : "",
            "active" : '成员列表',
            "allUser" : result
        });
    });
}